package com.hqyj.web.servlet;

import com.hqyj.pojo.Book;
import com.hqyj.pojo.User;
import com.hqyj.service.UserService;
import com.hqyj.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author cz
 * 2021/8/11 16:38
 */
@WebServlet("/login.do")
public class UserLoginServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("name");
        String password = req.getParameter("pass");
        User user = userService.loginUser(name, password);
        if (user != null){
            req.setAttribute("user",user);
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            List<Book> list = userService.findBookAll();
            req.setAttribute("list",list);
            if ("admin".equals(user.getRole())){
                req.getRequestDispatcher("/main.jsp").forward(req,resp);
            }else {
                req.getRequestDispatcher("/managermain.jsp").forward(req,resp);
            }
        }else {
            resp.sendRedirect("/index.jsp");
        }
    }
}
